package com.renting.modules.message.service;

import cn.jiguang.commom.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.renting.common.utils.DateUtils;
import com.renting.common.utils.SweetStringUtils;
import com.renting.modules.message.dao.MessageDao;
import com.renting.modules.message.entity.SimpleMessage;
import com.renting.modules.message.utils.PayLoadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service()
@Scope("application")
public class MessageService {

    protected static final Logger LOG = LoggerFactory.getLogger(MessageService.class);
    @Value("${appKey}")
    private String appKey;
    @Value("${masterSecret}")
    private String masterSecret;
    @Autowired
    private MessageDao messageDao;

    public void sendSimpleMessageToAll(SimpleMessage message) throws Exception {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload payload = PayLoadUtils.buildPushObject_android_alertWithTitle(message);
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
            /*最简单的message类型 新建直接发送 然后存储记录*/
            messageDao.save(addInfo(message, result));
        } catch (APIConnectionException e) {
            LOG.error("连接失败，请稍后重试", e);

        } catch (APIRequestException e) {
            LOG.error("得到了错误的响应", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    private SimpleMessage addInfo(SimpleMessage message, PushResult result) {
        message.setMsgId(String.valueOf(result.msg_id));
        message.setSendNo(String.valueOf(result.sendno));
        message.setId(SweetStringUtils.getUUIDNoBreak());
        message.setSendTime(DateUtils.getCurrent());

        return message;
    }




    public List findAll(SimpleMessage message) {
        List list = new ArrayList();
        messageDao.findAll().forEach((msg) -> list.add((SimpleMessage) msg));
        return list;
    }


}
